package job.work.config.filter;


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import job.work.domain.course.TokenIsExpiredException;
import job.work.domain.response.AuthCode;
import job.work.domain.response.ResponseResult;
import job.work.utils.JwtTokenUtils;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * Created by echisan on 2018/6/23
 */
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {
        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        String tokenHeader = request.getHeader("token");
        logger.info(tokenHeader + "=============前端传入token是");
        String requestUrl = request.getRequestURI();
        // 如果请求头中没有Authorization信息则直接放行了
        if (tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX) || requestUrl.contains("/auth") || requestUrl.contains("/csrf") ) {
            chain.doFilter(request, response);
            return;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        // 如果请求头中有token，则进行解析，并且设置认证信息
        try {
            SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));

        } catch (MalformedJwtException e) { //JWT格式错误
            logger.info("其他人登录！[{}====ms]");
            String rRString = JSON.toJSONString(new ResponseResult<>(AuthCode.AUTH_LOGIN_ERROR));
            String responseMessage = (String) JSON.parse(objectMapper.writeValueAsString(rRString));
            response.getWriter().write(responseMessage);
            return;
        } catch (SignatureException e) {//JWT非法令牌
            logger.error("50008,非法令牌", e);
            String rRString = JSON.toJSONString(new ResponseResult<>(AuthCode.AUTH_LOGIN_TOKEN_ILLEGAL));
            String responseMessage = (String) JSON.parse(objectMapper.writeValueAsString(rRString));
            response.getWriter().write(responseMessage);
            return;
        } catch (TokenIsExpiredException e) {//是JWT否过期
            //返回json形式的错误信息
            long endTime = System.currentTimeMillis();
            logger.info("令牌已过期！[{}ms]" + (endTime - startTime));
            String rRString = JSON.toJSONString(new ResponseResult<>(AuthCode.AUTH_LOGIN_TOKEN_TIME));
            String responseMessage = (String) JSON.parse(objectMapper.writeValueAsString(rRString));
            response.getWriter().write(responseMessage);
            return;
        }
        super.doFilterInternal(request, response, chain);
    }

    // 这里从token中获取用户信息并新建一个token
    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) throws TokenIsExpiredException {
        String token = tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, "");

        boolean expiration = JwtTokenUtils.isExpiration(token);
        if (expiration) {
            throw new TokenIsExpiredException("token超时了");
        } else {
            String username = JwtTokenUtils.getUsername(token);
            String role = JwtTokenUtils.getUserRole(token);
            logger.info(role + "登录人的权限是=====");
            if (username != null) {
                return new UsernamePasswordAuthenticationToken(username, null,
                        Collections.singleton(new SimpleGrantedAuthority(role))
                );
            }
        }
        return null;
    }
}
